// dao/category.js
import { connect } from '../db'
import { ensureConfigInitialized, serviceUrl } from '../config/config'

// 获取分类树
export async function getCategoryTree() {
  // 确保配置初始化完成
  await ensureConfigInitialized();

  const http_url = serviceUrl.baseUrlWithPort

  const response = await fetch(`${http_url}/apis/category/api/category/tree`);

  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }

  return await response.json();
}

// 获取子分类
export async function getSubCategories(parentId) {
  // 确保配置初始化完成
  await ensureConfigInitialized();

  const http_url = serviceUrl.baseUrlWithPort

  const response = await fetch(`${http_url}/apis/category/api/category/sub/${parentId}`);

  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }

  return await response.json();
}

// 添加分类
export async function addCategory(name, parentId, level) {
  // 确保配置初始化完成
  await ensureConfigInitialized();

  const http_url = serviceUrl.baseUrlWithPort

  const response = await fetch(`${http_url}/apis/category/api/category/add`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      name,
      parentId,
      level
    })
  });

  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }

  return await response.json();
}

// 更新分类
export function updateCategory(id, { name }) {
  const db = connect()
  const now = Date.now()
  const info = db.prepare(
    'UPDATE category SET name = ?, updated_at = ? WHERE id = ?'
  ).run(name, now, id)

  return info.changes > 0
}

// 删除分类
export async function deleteCategory(id) {
  // 确保配置初始化完成
  await ensureConfigInitialized();

  const http_url = serviceUrl.baseUrlWithPort
  const response = await fetch(`${http_url}/apis/category/api/category/delete/${id}`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    }
  });

  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }

  return await response.json();
}

// 检查视频是否重复
export function checkDuplicateVideo(fileMd5) {
  const db = connect()
  return db.prepare('SELECT * FROM video WHERE file_md5 = ?').get(fileMd5)
}

// 插入视频到库
export function insertVideoToLibrary(videoInfo) {
  const db = connect()
  const columns = Object.keys(videoInfo).join(', ')
  const placeholders = Object.keys(videoInfo).map(() => '?').join(', ')
  const values = Object.values(videoInfo)

  const info = db.prepare(`INSERT INTO video (${columns}) VALUES (${placeholders})`).run(...values)

  return info.lastInsertRowid
}
